<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus, Download, Refresh, Edit, Delete } from '@element-plus/icons-vue';

/**
 * 此页面对应账单中心的 发票管理
 */
// 查询条件
const queryForm = reactive({
  invoiceNo: '', // 发票号码
  waybillNo: '', // 运单号
  customer: '', // 客户
  invoiceStatus: '', // 发票状态
  startDate: '', // 开始日期
  endDate: '', // 结束日期
  invoiceType: '' // 发票类型
});

// 表格数据
const tableData = ref<any[]>([]);
// 表格加载状态
const loading = ref(false);
// 表格选中的行
const selectedRows = ref<any[]>([]);

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 发票状态选项
const invoiceStatusOptions = [
  { value: 'pending', label: '待开具' },
  { value: 'issued', label: '已开具' },
  { value: 'cancelled', label: '已作废' }
];

// 发票类型选项
const invoiceTypeOptions = [
  { value: 'special', label: '增值税专用发票' },
  { value: 'normal', label: '增值税普通发票' },
  { value: 'electronic', label: '电子发票' }
];

// 获取表格数据
const fetchTableData = async () => {
  loading.value = true;
  try {
    // 模拟数据
    const mockData = Array.from({ length: pagination.pageSize }, (_, index) => {
      const id = index + (pagination.currentPage - 1) * pagination.pageSize;
      return {
        id: `INV${1000 + id}`,
        invoiceNo: `FP${20230000 + id}`,
        waybillNo: `W${39000000 + id}`,
        customer: '王微微',
        invoiceStatus: id % 3 === 0 ? 'pending' : id % 3 === 1 ? 'issued' : 'cancelled',
        invoiceType: id % 3 === 0 ? 'special' : id % 3 === 1 ? 'normal' : 'electronic',
        amount: (1000 + Math.random() * 5000).toFixed(2),
        taxRate: '13%',
        taxAmount: (130 + Math.random() * 650).toFixed(2),
        totalAmount: (1130 + Math.random() * 5650).toFixed(2),
        createTime: '2023-10-15 14:30:00',
        issueTime: id % 3 === 1 ? '2023-10-16 10:15:00' : '',
        remark: ''
      };
    });

    tableData.value = mockData;
    pagination.total = 50; // 模拟总数据量
  } catch (error) {
    console.error('获取数据失败', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 重置查询条件
const resetQueryForm = () => {
  Object.keys(queryForm).forEach(key => {
    (queryForm as any)[key] = '';
  });
  handleSearch();
};

// 查询数据
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchTableData();
};

// 处理表格选择变化
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

// 处理分页变化
const handlePageChange = (currentPage: number) => {
  pagination.currentPage = currentPage;
  fetchTableData();
};

// 处理每页条数变化
const handleSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize;
  pagination.currentPage = 1;
  fetchTableData();
};

// 开具发票
const handleIssueInvoice = (row: any) => {
  ElMessageBox.confirm(
    `确定要开具发票吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('发票开具成功');
    fetchTableData();
  }).catch(() => {});
};

// 作废发票
const handleCancelInvoice = (row: any) => {
  ElMessageBox.confirm(
    `确定要作废该发票吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('发票作废成功');
    fetchTableData();
  }).catch(() => {});
};

// 页面加载时获取数据
onMounted(() => {
  fetchTableData();
});
</script>

<template>
  <div class="invoice-manage-view">
    <div class="page-header">
      <h2 class="page-title">发票管理</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="queryForm" inline>
        <el-form-item label="发票号码">
          <el-input v-model="queryForm.invoiceNo" placeholder="请输入发票号码" clearable></el-input>
        </el-form-item>
        
        <el-form-item label="运单号">
          <el-input v-model="queryForm.waybillNo" placeholder="请输入运单号" clearable></el-input>
        </el-form-item>

        <el-form-item label="客户">
          <el-input v-model="queryForm.customer" placeholder="请输入客户名称" clearable></el-input>
        </el-form-item>

        <el-form-item label="发票状态">
          <el-select v-model="queryForm.invoiceStatus" placeholder="请选择" clearable>
            <el-option
              v-for="item in invoiceStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="发票类型">
          <el-select v-model="queryForm.invoiceType" placeholder="请选择" clearable>
            <el-option
              v-for="item in invoiceTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="开票日期">
          <el-date-picker
            v-model="queryForm.startDate"
            type="date"
            placeholder="开始日期"
            style="width: 150px"
          />
          <span class="date-separator">至</span>
          <el-date-picker
            v-model="queryForm.endDate"
            type="date"
            placeholder="结束日期"
            style="width: 150px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetQueryForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格工具栏 -->
    <div class="table-toolbar">
      <div class="left">
        <el-button type="primary" :icon="Plus">批量开票</el-button>
      </div>
      <div class="right">
        <el-button :icon="Download" @click="exportData">导出</el-button>
      </div>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="invoiceNo" label="发票号码" width="150" />
      <el-table-column prop="waybillNo" label="运单号" width="150" />
      <el-table-column prop="customer" label="客户" width="120" />
      <el-table-column prop="invoiceType" label="发票类型" width="150">
        <template #default="{ row }">
          <el-tag
            :type="row.invoiceType === 'special' ? 'success' : row.invoiceType === 'normal' ? 'warning' : 'info'"
          >
            {{ invoiceTypeOptions.find(item => item.value === row.invoiceType)?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="amount" label="金额" width="120" />
      <el-table-column prop="taxRate" label="税率" width="100" />
      <el-table-column prop="taxAmount" label="税额" width="120" />
      <el-table-column prop="totalAmount" label="价税合计" width="120" />
      <el-table-column prop="invoiceStatus" label="状态" width="100">
        <template #default="{ row }">
          <el-tag
            :type="row.invoiceStatus === 'issued' ? 'success' : row.invoiceStatus === 'pending' ? 'warning' : 'danger'"
          >
            {{ invoiceStatusOptions.find(item => item.value === row.invoiceStatus)?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="issueTime" label="开票时间" width="180" />
      <el-table-column label="操作" fixed="right" width="150">
        <template #default="{ row }">
          <el-button
            v-if="row.invoiceStatus === 'pending'"
            type="primary"
            link
            @click="handleIssueInvoice(row)"
          >开具</el-button>
          <el-button
            v-if="row.invoiceStatus === 'issued'"
            type="danger"
            link
            @click="handleCancelInvoice(row)"
          >作废</el-button>
          <el-button type="primary" link>打印</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<style scoped>
.invoice-manage-view {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  margin: 0;
}

.search-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.date-separator {
  margin: 0 10px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>